//
//  HFQAuthViewController.swift
//  sinaMicroBlog
//
//  Created by mac on 15/11/11.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class HFQAuthViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadOAthPage()
    }
    
    let webView = UIWebView()
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    //设置关闭按钮
    private func setupUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fillAccount")
    }
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func fillAccount() {
        let jsString = "document.getElementById('userId').value = '18369905835' , document.getElementById('passwd').value = 'l112r150f4496hh!';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    //加载网络页面
    private func loadOAthPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
}
extension HFQAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    
        //验证URL是否正确
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        if urlString.hasPrefix("https://api.weibo.com") {
            return true
        }
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        guard let query = request.URL?.query else {
            return false
        }
        
        let codeString = "code="
        let code = query.substringFromIndex(codeString.endIndex)
        
        print(query)
        print(code)
        //获取用户token
        HFUserAccountViewModel().loadAccessToken(code) { (error) -> () in
            
            if error != nil {
                SVProgressHUD.showInfoWithStatus(AppError)
                return
            }
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewController, object: "welcome")
            })
        }
        
        return false
    }
 
}




